package com.test.demo.io.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class NIOSocketServer {

    private static List<SocketChannel> list=new ArrayList<>();
    public static void main(String[] args) throws IOException {
        //创建NIOSocketChannel
        ServerSocketChannel socketChannel = ServerSocketChannel.open();
        socketChannel.bind(new InetSocketAddress(9000));
        //等待连接的时候设置非阻塞
        socketChannel.configureBlocking(false);
        System.out.println("NIOSocketServer 启动了");

        while (true){
            SocketChannel accept = socketChannel.accept();
            if (accept!=null){
                System.out.println("客户端连接成功");
                //在执行读的时候也进行非阻塞
                accept.configureBlocking(false);
                list.add(accept);
            }

            Iterator<SocketChannel> iterator = list.iterator();
            while (iterator.hasNext()){
                SocketChannel socket1 = iterator.next();

                ByteBuffer byteBuffer = ByteBuffer.allocate(128);
                int read = socket1.read(byteBuffer);
                if (read>0){
                    System.out.println("收到客户端数据"+new String(byteBuffer.array()));
                }else if (read==-1){
                    list.remove(socket1);
                    System.out.println("客户端关闭了");
                }
            }
        }
    }
}
